-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.cpp
More file actions
61 lines (49 loc) · 1.13 KB
/
Solution.cpp
File metadata and controls
61 lines (49 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;
while (current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
int main() {
int n, value;
cout << "Enter the number of nodes: ";
cin >> n;
Node *head = nullptr, *tail = nullptr;
for (int i = 0; i < n; i++) {
cout << "Enter value for node " << i + 1 << ": ";
cin >> value;
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
cout << "Original List: ";
printList(head);
head = reverseList(head);
cout << "Reversed List: ";
printList(head);
return 0;
}